<template>
	<view class="container">
		<view class="search-box">
			<uni-search-bar @input="onSearchInput" v-model="searchKeyword" placeholder="订单号/申请人/物品名称" />
		</view>
		<view class="filter-container">
			<uni-segmented-control :current="status" :values="items" :style-type="'button'" :active-color="'#18bc37'"
				@clickItem="onClickItem" class="segmented-control" />
		</view>

		<view v-if="recordList.length === 0" class="empty-state">
			<image src="/static/avatar/empty.png" mode="aspectFit" class="empty-image"></image>
			<text class="empty-text">暂无相关申请记录</text>
		</view>


		<view v-for="(record, index) in recordList" :key="index">
			<view class="order-id-container">
				<text class="order-id-label">订单号：</text>
				<text class="order-id">{{ record.order_id }}</text>
			</view>
			<uni-card :is-shadow="true" margin="20rpx 0" @tap="viewDetail(record._id)">
				<template v-slot:title>
					<view class="card-header">
						<text class="time">申请人：{{ record.user_name }}</text>
						<text class="time"> {{ formatDate(record.create_date) }}</text>
						<uni-tag :text="getStatusText(record.status)"
							:type="statusTypeMap[record.status] || 'default'"></uni-tag>
					</view>
				</template>

				<uni-list>
					<uni-list-item :border="false">
						<template v-slot:body>
							<view class="goods-container">
								<!-- 商品信息 -->
								<view class="goods-info">
									<image class="goods-thumb" :src="record.goods.thumb || defaultThumb"
										mode="aspectFill" @click="previewImage(record.goods.thumb)" />
									<view class="goods-content">
										<view class="goods-title">
											<text class="">{{ record.goods.name }}</text>
											<uni-tag class="tag" :text="getStatusText2(record.goods.status)"
												:type="statusTypeMap2[record.goods.status] || 'default'"></uni-tag>
										</view>
										<view class="goods-desc">
											<text class="desc-text"
												v-if="record.goods.brand">{{ record.goods.brand }}</text>
											<text class="desc-text"
												v-if="record.goods.model">{{ record.goods.model }}</text>
										</view>
										<view class="goods-desc">{{ record.goods.desc }}</view>
										<view class="goods-count">领取数量：{{ record.goods._cartNumber }}</view>
									</view>
								</view>

								<!-- 底部操作按钮 -->
								<view class="action-buttons" v-if="record.goods.status === 4">
									<button class="btn return" @tap="handleReturn(record.goods, record._id, 1)"
										v-if="record.goods.status === 4">核准</button>
								</view>
							</view>
						</template>
					</uni-list-item>
				</uni-list>

				<template>
					<view class="action-buttons" v-if="record.status === 0">
						<button class="btn return" @tap.stop="openNoteDialog(record)">核准</button>
						<button class="btn loss" @tap.stop="openRejectDialog(record)">驳回</button>
					</view>
					<view class="refuse" v-if="record.status === 1">
						<text class="refuse-text">备注：{{record.note}}</text>
					</view>
					<view class="refuse" v-if="record.status === 2">
						<text class="refuse-text">驳回理由：{{record.refuse}}</text>
					</view>
				</template>
			</uni-card>
		</view>

		<!-- 审核备注输入弹窗 -->
		<uni-popup ref="noteDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="核准" placeholder="请输入信息"
				@confirm="submitNote"></uni-popup-dialog>
		</uni-popup>

		<!-- 驳回原因输入弹窗 -->
		<uni-popup ref="refuseDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="驳回" placeholder="请输入驳回原因"
				@confirm="submitReject"></uni-popup-dialog>
		</uni-popup>

		<!-- 加载状态提示 -->
		<view class="load-more-container">
			<uni-load-more :status="loadStatus" :content-text="{
		                    contentdown: '上拉加载更多',
		                    contentrefresh: '正在加载...',
		                    contentnomore: '没有更多数据了'
		                  }" icon-type="circle" />
		</view>
	</view>

</template>

<script>
	export default {
		data() {
			return {
				searchKeyword: '',
				selectedRecord: null, // 当前选中的记录
				defaultThumb: '/static/avatar/empty.png',
				recordList: [],
				statusTypeMap: {
					0: 'warning', // 待核准
					1: 'success', // 已核准
					2: 'error', // 已驳回
					3: 'default' // 已取消
				},
				statusTypeMap2: {
					0: 'default', // 领用中
					1: 'success', // 归还
					2: 'warning', // 遗失
					3: 'error' // 损坏
				},
				items: ['待核准', '已核准', '已驳回', '已取消'],
				loadStatus: 'more',
				status: 0,
				currentPage: 1,
				pageSize: 10,
				// 防抖用的 timer
				searchTimer: null,
				// 新增加载状态相关数据
				isLoadMore: false,
				total: 0,
			}
		},
		mounted() {
			this.initData()
		},
		onPullDownRefresh() {
			this.handleRefresh();
		},
		onReachBottom() {
			this.handleLoadMore();
		},
		methods: {
			onSearchInput() {
				clearTimeout(this.searchTimer);
				this.searchTimer = setTimeout(() => {
					this.initData();
				}, 1000)
			},
			async initData() {
				//console.log('initData')
				await this.fetchRecords()
			},
			handleRefresh() {
				this.currentPage = 1;
				this.fetchRecords().finally(() => {
					uni.stopPullDownRefresh();
				});
			},
			// 上拉加载更多处理
			handleLoadMore() {
				if (this.loadStatus === 'noMore' || this.isLoadMore) return;

				this.isLoadMore = true;
				this.currentPage += 1;
				this.fetchRecords(true);
			},
			async fetchRecords(isLoadMore = false) {
				//console.log('fetchRecords', this.loadStatus)
				try {
					// if (this.loadStatus === 'noMore') return;

					const params = {
						status: this.status,
						keyword: this.searchKeyword,
						page: this.currentPage,
						pageSize: this.pageSize
					};
					const goodsObj = uniCloud.importObject('goods');
					const res = await goodsObj.getGoodsRecord(params);
					if (res.code === 0) {
						this.total = res.total;
						if (isLoadMore) {
							this.recordList = [...this.recordList, ...res.data];
						} else {
							this.recordList = res.data;
						}

						// 更新加载状态
						this.loadStatus = this.recordList.length >= this.total ? 'noMore' : 'more';
					}
				} catch (e) {
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					this.isLoadMore = false;
				}
			},
			formatDate(dateStr) {
				return dateStr ? dateStr.replace('T', ' ').substr(0, 16) : ''
			},
			getStatusText(status) {
				const statusMap = {
					0: '待核准',
					1: '已核准',
					2: '已驳回',
					3: '已取消'
				}
				return statusMap[status] || '未知状态'
			},
			getStatusText2(status) {
				const statusMap = {
					0: '正常',
					1: '归还',
					2: '遗失',
					3: '损坏',
					4: '归还中'
				}
				return statusMap[status] || '未知状态'
			},
			previewImage(url) {

			},
			viewDetail(id) {
				uni.$router.to({
					url: '/pagesA/item/goods/detail', // 根据实际路由调整
					params: {
						_id: id
					}
				})
			},
			//打开审核弹窗
			openNoteDialog(record) {
				this.selectedRecord = record
				this.$refs.noteDialog.open()
			},
			// 打开驳回弹窗
			openRejectDialog(record) {
				this.selectedRecord = record
				this.$refs.refuseDialog.open()
			},
			onClickItem(e) {

				if (this.status !== e.currentIndex) {
					this.status = e.currentIndex
				}
				//console.log('onClickItem', e, this.status)
				this.initData()
			},
			//审核备注
			async submitNote(value) {
				if (!value) {
					uni.showToast({
						icon: "error",
						title: "请输入内容"
					})
					return
				}
				if (!this.selectedRecord) return

				// //console.log(value, "submitNote")
				const obj = uniCloud.importObject('goods')
				const res = await obj.updateRecordStatus({
					_id: this.selectedRecord._id,
					status: 1,
					data: this.selectedRecord.goods,
					approve_name: uni.getStorageSync('userInfo').username,
					approve_date: uni.$dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
					note: value || ''
				})

				if (res.code == 0) {
					uni.showToast({
						icon: "success",
						title: res.message
					})
					// 刷新数据
					setTimeout(() => {
						this.initData()
					}, 1000);
				}

				// 清空数据				
				this.selectedRecord = null
			},
			// 提交驳回原因
			async submitReject(value) {
				if (!value) {
					uni.showToast({
						icon: "error",
						title: "请输入原因"
					})
					return
				}
				if (!this.selectedRecord) return

				const obj = uniCloud.importObject('goods')
				const res = await obj.updateRecordStatus({
					_id: this.selectedRecord._id,
					status: 2,
					data: this.selectedRecord.goods,
					approve_name: uni.getStorageSync('userInfo').username,
					approve_date: uni.$dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
					refuse: value || ''
				})

				if (res.code == 0) {
					uni.showToast({
						icon: "success",
						title: res.message
					})
					// 刷新数据
					setTimeout(() => {
						this.initData()
					}, 1000);
				}

				// 清空数据				
				this.selectedRecord = null
			},

			// 归还商品
			async handleReturn(goods, recordid, type) {
				if (goods.status !== 4) {
					uni.showToast({
						title: '该商品状态不可操作',
						icon: 'none'
					});
					return;
				}
				uni.showModal({
					title: '提示',
					content: '确认归还该商品？',
					success: async (res) => {
						if (res.confirm) {
							const obj = uniCloud.importObject('goods')
							const result = await obj.updateGoodsRecordGoodsStatus({
								_id: recordid,
								data: {
									_id: goods._id,
									status: type,
									_cartNumber: goods._cartNumber
								}
							})
							if (result.code == 0) {
								uni.showToast({
									icon: "success",
									title: result.message
								});
								setTimeout(() => {
									this.initData();
								}, 1000);
							}
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 20rpx;
		background: #f8f8f8;
		min-height: 100vh;
	}

	.goods-container {
		display: flex;
		flex-direction: column;
		padding: 20rpx 0;
	}

	.goods-info {
		display: flex;
		align-items: flex-start;

		.goods-thumb {
			width: 180rpx;
			height: 180rpx;
			border-radius: 8rpx;
			margin-right: 20rpx;
			flex-shrink: 0;
		}

		.goods-content {
			flex: 1;
			min-width: 0;
			width: 100%;

			.goods-title {
				font-size: 30rpx;
				color: #333;
				line-height: 1;
				font-weight: bold;
				display: flex;
				justify-content: space-between;
				align-items: center;
				width: 100%;

				.tag {
					transform: scale(0.8);
					transform-origin: right center;
					margin-left: 20rpx;
					flex-shrink: 0;
				}
			}

			.goods-desc {
				overflow: hidden;
				margin-top: 10rpx;
				display: flex;
				align-content: center;
				align-items: center;
				font-size: 24rpx;

				.desc-text {
					background-color: #FAEFF7;
					padding: 2rpx 10rpx;
					box-sizing: border-box;
					color: #e11d48;
					border-radius: 10rpx;
					margin-right: 15rpx;
				}
			}

			.goods-count {
				font-size: 26rpx;
				color: #007AFF;
			}
		}
	}

	.action-buttons {
		display: flex;
		justify-content: center;
		gap: 20rpx;
		border-top: 1rpx dashed #eee;
		padding: 20rpx 0 0;

		.btn {
			min-width: 120rpx;
			height: 45rpx;
			line-height: 45rpx;
			border-radius: 12rpx;
			font-size: 28rpx;
			padding: 0 20rpx;
			margin: 0;
			transition: all 0.2s;

			&::after {
				border: none;
			}

			&.return {
				background: #18bc37;
				color: #fff;
			}

			&.loss {
				background: #dd524d;
				color: #fff;
			}

			&:active {
				opacity: 0.8;
				transform: scale(0.95);
			}
		}
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10rpx 0;

		.time {
			font-size: 26rpx;
			color: #000000;
		}
	}

	.filter-container {
		padding: 20rpx 20rpx 0;
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.segmented-control {
		.uni-segmented-control__item {
			flex: 1;
			min-width: 160rpx; // 设置每个按钮的最小宽度
			margin: 0 10rpx; // 按钮之间留出间距
			border-radius: 40rpx;
			background-color: #f0f0f0;
			color: #666;
			transition: all 0.3s ease;

			&.uni-segmented-control__item--active {
				background-color: #18bc37;
				color: #fff;
			}
		}
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 80rpx 0;

		.empty-image {
			width: 300rpx;
			height: 300rpx;
			opacity: 0.6;
		}

		.empty-text {
			font-size: 30rpx;
			color: #999;
			margin-top: 30rpx;
		}
	}

	.refuse {
		flex: 1;
		flex-direction: row;
		padding-top: 10rpx;

		.refuse-text {
			color: #ff0000;
		}
	}

	.order-id-container {
		display: inline-block;
		padding: 4rpx 16rpx;
		border-radius: 8rpx;
		background-color: #f0f0f0;
		margin: 8rpx 0;
	}

	.order-id-label {
		font-weight: bold;
		color: #5555ff;
	}

	.order-id {
		color: #5555ff;
		font-family: monospace; // 使用等宽字体提升可读性
	}

	.load-more-container {
		padding: 20rpx 0;
		background-color: #f8f8f8;
	}

	.search-box {
		background: #fff;
		padding: 5rpx;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
	}
</style>